package com.example.iread.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.os.IBinder;

import com.example.iread.R;
import com.example.iread.activity.AudioPlayerActivity;
import com.example.iread.application.MyApplication;

public final class FloatWindowUtil {

    private final String TAG = "SoRiya";

    @SuppressLint("StaticFieldLeak")
    private static FloatWindowUtil instance;

    MyApplication application = MyApplication.getInstance();

    private static WindowManager.LayoutParams params;

    private View floatView;
    private WindowManager windowManager;
    private DisplayMetrics displayMetrics;

    private Activity activity;

    private float x1, x2;
    private float y1, y2;

    public boolean isHide = true;

    public String chapterName = "IRead";

    private FloatWindowUtil() {}

    public static FloatWindowUtil getInstance() {
        if (instance == null) instance = new FloatWindowUtil();
        return instance;
    }

    @SuppressLint("ClickableViewAccessibility")
    private void init() {
        params = new WindowManager.LayoutParams(
                DensityUtil.dpToPx(application, 50),
                DensityUtil.dpToPx(application, 50),
                WindowManager.LayoutParams.TYPE_APPLICATION_PANEL,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
        );

        params.gravity = Gravity.START | Gravity.TOP;
        params.x = 0;
        params.y = 200;

        floatView = LayoutInflater.from(application).inflate(R.layout.float_audio_player, null);

        floatView.setOnTouchListener((v, e) -> {
            switch (e.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    // 得到相对应屏幕左上角的坐标
                    x1 = e.getRawX();
                    y1 = e.getRawY();
                    return true;
                case MotionEvent.ACTION_UP:
                    x2 = e.getRawX();
                    y2 = e.getRawY();
                    // 两点之间的距离
                    double distance = Math.sqrt(Math.abs(x1 - x2) * Math.abs(x1 - x2) + Math.abs(y1 - y2) * Math.abs(y1 - y2));
                    if (distance < 15) {
                        // 距离较小，当作click事件来处理
                        Intent intent = new Intent(activity, AudioPlayerActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("chapterName", chapterName);
                        application.startActivity(intent);
                        return false;
                    } else {
                        float rawX = e.getRawX();
                        int edgeX = (int) rawX - (displayMetrics.widthPixels / 2);

                        params.x = edgeX < 0 ? 0 : displayMetrics.widthPixels - DensityUtil.dpToPx(application, 50);
                        windowManager.updateViewLayout(floatView, params);
                        return true;
                    }
                case MotionEvent.ACTION_MOVE:
                    params.x = (int) e.getRawX();
                    params.y = (int) e.getRawY();
                    windowManager.updateViewLayout(floatView, params);
                    return true;
                default:
                    return false;
            }
        });

        windowManager = (WindowManager) application.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);

        displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
    }

    public void show(Activity activity) {
        this.activity = activity;
        if (!isHide) return;
        if (floatView == null || params == null) init();
        isHide = false;
        params.token = activity.getWindow().getDecorView().getWindowToken();
        windowManager.addView(floatView, params);
    }

    public void updateToken(Activity activity) {
        if (params == null || isHide) return;
        this.activity = activity;
        IBinder windowToken = activity.getWindow().getDecorView().getWindowToken();
        try {
            windowManager.removeView(floatView);
        } catch (IllegalArgumentException e) {
            Log.i(TAG, "removeView: error");
        } finally {
            params.token = windowToken;
            windowManager.addView(floatView, params);
        }
    }

    public void hide(Activity activity) {
        if (isHide) return;
        isHide = true;
        params.token = activity.getWindow().getDecorView().getWindowToken();
        windowManager.removeView(floatView);
    }
}
